<template>
	<view>
		<view class="bg-gradual-blue">
			<!-- <view :style="{'padding-top': menuButtonTop}"></view> -->
			<!-- 切换身份 -->
			<!-- <change-identities bg="#ffffff"></change-identities> -->
			<view class="header" :style="{'padding-top': menuButtonTop}">
				<view class="u-flex" style="justify-content: left;" :style="{'padding-right':menuButtonWidth}">
					<view class="u-p-r-20" style="display: flex;align-items: center;">
						<!-- <image v-if="webSetting.adminlogoimg" :src="webSetting.adminlogoimg" mode="heightFix" :style="{'height':menuButtonHeight,'weight':menuButtonHeight,'border-radius':'50%'}"></image>
						<text class="u-font-36 bold-txt u-p-l-6" style="white-space: nowrap;">猿哥</text> -->
					</view>
					<view style="background-color: #fff;border-radius: 8rpx;">
						<!-- <u-input v-model="key" :border="true" :height="50" clearable/> -->
						<u-search placeholder="搜索单号" v-model="key" shape="square" :show-action="false" :height="50" :input-style="{'flex': 1}"></u-search>
					</view>
				</view>
				<!-- <view class="u-flex u-p-t-30">
					<view class="left">
						<navigator url="../order/mapList/mapList" class="icon-box" :style="{'height':menuButtonHeight,'width':menuButtonHeight}">
							<u-icon name="map-fill" color="#fff" size="40"></u-icon>
						</navigator>
					</view>
					<view>
						<text class="u-font-32">回收订单</text>
					</view>
					<view class="right">
						<view class="select" :style="{'height':menuButtonHeight}">
							<view @click="show = true" style="display: flex;align-items: center;">
								<view class="online" v-if="online">
									<text class="poin"></text>
									<text class="u-p-r-20">上线中</text>
								</view>
								<view class="offline" v-else>
									<text class="poin"></text>
									<text class="u-p-r-20">已下线</text>
								</view>
								<u-icon name="arrow-down-fill" color="#fff" size="14"></u-icon>
							</view>
							<u-action-sheet :list="actionSheetList" v-model="show" @click="actionSheetCallback">
							</u-action-sheet>
						</view>
					</view>
				</view> -->
			</view>

			<view class="u-tabs-box">
				<u-tabs :list="list" activeColor="#ffffff" inactive-color="#ffffff" bg-color="rgba(0,0,0,0)" :is-scroll="true" :current="current" @change="change"></u-tabs>
			</view>
		</view>

		<view class="u-p-l-30 u-p-t-30 u-p-r-30 u-p-b-10" v-if="address">
			<u-icon name="map-fill" class="u-tips-color"></u-icon><text><text class="u-tips-color">当前位置：</text>{{address}}</text>
		</view>

		<!-- 订单列表 -->
		<view class="order-list">
			<view class="page-box" v-if="orderList.length > 0">
				<userOrderList :orderList="orderList"></userOrderList>
				<u-loadmore :status="loadStatus"></u-loadmore>
			</view>
			<view v-else class="u-h-500">
				<u-empty text="您还没有相关的订单" mode="list"></u-empty>
			</view>
		</view>
		
		<!-- 底部菜单 -->
		<tabbar :current="0"></tabbar>

		<!-- 菜单 -->
		<!-- <u-popup v-model="showMenu" mode="left" width="550rpx">
			<homeSlice></homeSlice>
		</u-popup> -->
	</view>
</template>

<script>
	import { mapState } from 'vuex';
	// import homeSlice from '../components/homeSlice/homeSlice.vue'
	import tabbar from '../components/tabbar/tabbar.vue'
	import userOrderList from '../components/user-order-list/user-order-list.vue'
		
	export default {
		components:{
			// homeSlice,
			tabbar,
			userOrderList
		},
		data() {
			return {
				menuButtonTop: '44px',
				menuButtonHeight: '30px',
				menuButtonWidth: '50px',
				logoHeight: '32px',
				key: '',
				PageIndex: 1,
				PageSize: 20,
				showMenu: false,
				show: false,
				actionSheetList: [{
					text: '上线',
					color: '#000',
					fontSize: 28,
				}, {
					text: '下线',
					color: '#000',
					fontSize: 28,
				}],
				stateList:[
					{
						"value": 1,
						"name": "待接单",
						"count": 0
					},
				],
				list: [
					{
						"value": null,
						"name": "全部",
						"count": 0
					}, 
					{
						"value": 1,
						"name": "待接单",
						"count": 0
					}, 
					{
						"value": 2,
						"name": "已接单",
						"count": 0
					}, 
					{
						"value": 3,
						"name": "待上门",
						"count": 0
					}, 
					{
						"value": 4,
						"name": "待付款",
						"count": 0
					}, 
					{
						"value": 6,
						"name": "已回收",
						"count": 0
					}, 
					{
						"value": 5,
						"name": "已取消",
						"count": 0
					}, 
					// {
					// 	"value": 7,
					// 	"name": "待入库",
					// 	"count": 0
					// }, 
					// {
					// 	"value": 8,
					// 	"name": "已入库",
					// 	"count": 0
					// }
				],
				current: 0,
				orderList: [],
				loadStatus: 'loading',
				address: ''
			}
		},
		computed: {
			...mapState({
				userdetail: state => state.userdetail,
				webSetting: state => state.webSetting
			}),
			...mapState('brother',{
				online: state => state.online,
				brotherTrip: state => state.brotherTrip
			})
		},
		watch:{
			key(val){
				this.getOrderList(this.list[this.current].value, this.current,true)
			}
		},
		onShow(){
			// #ifdef MP-WEIXIN
			this.menuButtonTop = wx.getMenuButtonBoundingClientRect().top + 'px'
			this.menuButtonHeight = wx.getMenuButtonBoundingClientRect().height + 'px'
			this.menuButtonWidth = wx.getMenuButtonBoundingClientRect().width + 20 + 'px'
			// #endif
			
			// 获取小哥上线状态
			this.$store.dispatch('brother/getBrotherOnlineState')
			// 获取小哥当前位置
			this.$store.dispatch('brother/getBrotherTrip').then((res)=>{
				// console.log('brotherTrip',this.$store.state.brother.brotherTrip,this.brotherTrip)
				if(!res){
					return
				}
				const key = 'd1a7ea2dc24fa8ae4b0b10eac185ad5d'
				wx.request({
					url: `https://restapi.amap.com/v3/geocode/regeo?location=${res.longitude},${res.latitude}&key=${key}`,
					success: (res) => {
						console.log('regeo',res)
						// this.address = res.data.regeocode.formatted_address
						this.address = res.data.regeocode.addressComponent.city + res.data.regeocode.addressComponent.district + res.data.regeocode.addressComponent.township + res.data.regeocode.addressComponent.streetNumber.street + res.data.regeocode.addressComponent.streetNumber.number
					},
					fail: (err) => {
						console.log('err:',err)
					},
					complete: () => {
						uni.hideLoading()
						this.loading = false
					}
				})
			}).finally(()=>{
				this.orderList = []
				this.getOrderList(this.list[this.current].value, this.current, true);
			})
		},
		onReachBottom(e) {
			this.reachBottom()
		},
		methods: {
			reachBottom() {
				// 此tab为空数据
				this.PageIndex += 1
				if (!this.noMore) {
					this.getOrderList(this.list[this.current].value, this.current).then((row) => {
						if (row.length == 0) {
							this.noMore = true
						}
					})
				}
			},
			// 上线
			actionSheetCallback(index) {
				if (index == 0) { //当点击’上线中‘时
					uni.showModal({
						title: '是否确认上线？',
						content: '上线后后台可以给您指派订单',
						success: (res)=> {
							if (res.confirm) {
								console.log('用户点击确定');
								
								uni.showLoading({
									title: '正在上线...'
								})

								// #ifdef H5
								let origin = {
									lng:0,
									lat:0
								}
								this.$u.post('/Brother/Trip/Online',origin).then((res)=>{
									this.$store.commit('brother/setOnline', true)
									uni.showToast({
										title: '已上线',
										icon: 'none'
									})
									uni.hideLoading()
								}).catch((err)=>{
									uni.hideLoading()
								})
								// #endif

								// #ifdef MP-WEIXIN
								uni.getLocation({
									type: 'gcj02',
									geocode: true,
									success: res=> {
										console.log('当前位置的经度：' + res.longitude);
										console.log('当前位置的纬度：' + res.latitude);
										
										let origin = {
											lng:res.longitude,
											lat:res.latitude
										}
										
										this.$u.post('/Brother/Trip/Online',origin).then((res)=>{
											this.$store.commit('brother/setOnline', true)
											// this.$store.dispatch('getBrotherTrip')
											uni.showToast({
												title: '已上线',
												icon: 'none'
											})
											uni.hideLoading()
										}).catch((err)=>{
											uni.hideLoading()
										})
									}
								});
								// #endif
								
								// this.$store.dispatch('signalrConnection').then(()=>{
								// 	uni.navigateTo({
								// 		url: '/pages/index/index'
								// 	})
								// })
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					})
				}else{
					// this.$store.dispatch('signalrConnection').then((connection)=>{
					// 	connection.closeMessage()
					// })
					// this.$store.commit('setOnline', false)
					this.$u.post('/Brother/Trip/Offline').then((res)=>{
						this.$store.commit('brother/setOnline', false)
						uni.showToast({
							title: '已下线',
							icon: 'none'
						})
					})
					console.log('用户点击取消');
				}
			},
			// tab栏切换
			change(index) {
				this.PageIndex = 1;
				this.current = index;
				this.current = index;
				this.orderList = [];
				this.noMore = false;
				// this.getOrderList(index);
				this.getOrderList(this.list[this.current].value, index, true);
			},
			// 页面数据
			getOrderList(idx, index, renew = false) {
				return new Promise((resolve, reject) => {
					this.loadStatus = 'loading'
					if (renew) {
						this.PageIndex = 1
					}

					this.$u.post('/User/Order/List', {
						"PageIndex": this.PageIndex,
						"PageSize": this.PageSize,
						"key": this.key,
						"manageState": idx,
						"orderType": 1, //只查询线上订单
						// "Order": [{column:'Sort', isdesc: true}, {column:'Id', isdesc: true}],
						// "assignmentState": 0,
						// "state": [0, 1, 2, 3, 4, 5],
						// "manageState": 0
					}).then((res) => {
						res.managestate.forEach((item)=>{
							this.list.forEach((cell)=>{
								if((item.value == cell.value) && (cell.value == 1 || cell.value == 2 || cell.value == 3 || cell.value == 4)){
									cell.count = item.count
								}
							})
						})
						
						console.log('this.list',this.list)
						
						this.refreshing = false
						// 是否刷新列表
						if (renew) {
							this.orderList = res.rows
							this.loadStatus = "nomore"
						} else {
							if (res.rows.length > 0) {
								res.rows.forEach((item) => {
									this.orderList.push(item)
								})
								if (res.rows.length < this.PageSize) {
									this.loadStatus = "nomore"
								} else {
									this.loadStatus = "loadmore"
								}
							} else {
								this.loadStatus = "nomore"
							}
						}
						
						// 定位小哥位置，按距离排序订单
						console.log('小哥当前位置:',this.brotherTrip)
						let latitude = this.$store.state.brother.brotherTrip.latitude
						let longitude = this.$store.state.brother.brotherTrip.longitude
						
						// let latitude= 23.623159
						// let longitude= 113.042491
						
						this.orderList.forEach(item => {
							// // 格式化状态显示
							// console.log('this.list.find((cell)=>cell.name == item.managestate)',this.list.find((cell)=>cell.name == item.managestate))
							// item.managestateName = this.list.find((cell)=>cell.name == item.managestate).name
							
							// 距离计算公式
							var radweidu1 = this.Rad(latitude);
							var radweidu2 = this.Rad(item.address.lat);
							var a = radweidu1 - radweidu2;
							var b = this.Rad(longitude) - this.Rad(item.address.lng);
							// console.log(b);
							var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radweidu1) * Math.cos(radweidu2) * Math.pow(Math.sin(b / 2), 2)));
							// console.log(s);
							s = s * 6378.137;
							s = Math.round(s * 10000) / 10000;
							s = s.toFixed(1) //保留两位小数
							// console.log('经纬度计算的距离:' + s)
							item.distance = parseFloat(s)
						})
						
						// 按距离排序
						if(index < 4){ //待接单、已接单、待上门、待付款按当前定位到客户地址距离排序
							this.orderList.sort(function(a, b) {
								if (a.distance > b.distance) {
									return 1;
								} else if (a.distance < b.distance) {
									return -1
								} else {
									return 0;
								}
							})
						}
						
						// 过滤已入库，未入库
						// this.orderList = this.orderList.filter((item)=>item.state != '待入库' || item.state != '已入库')
						
						this.$forceUpdate()
						resolve(res.rows)
					}).catch((err) => {
						console.log('获取订单列表报错:',err)
						this.refreshing = false
						reject()
					})
				})
			},
			// 计算距离函数
			Rad(d) {
				// console.log(d,'这里是D');
				//根据经纬度判断距离
				return d * Math.PI / 180.0;
			}
		}
	}
</script>

<style lang="scss" scoped>
	.header {
		width: 100%;
		box-sizing: border-box;
		padding: 70rpx 7px 10rpx 7px;

		/* #ifdef MP-WEIXIN */
		padding-top: calc(22px + var(--status-bar-height));
		/* #endif */
		.u-flex{
			align-items: center;
			justify-content: space-between;
		}
		
		.left {
			width: 240rpx;
			display: flex;
			align-items: center;
	
			.person {
				margin-left: 30rpx;
	
				.name {
					.text {
						margin-right: 10rpx;
					}
				}
	
				.logon {
					margin-top: 10rpx;
				}
			}
		}
	
		.right {
			width: 240rpx;
			display: flex;
			justify-content: flex-end;
		}
		
		.select {
			margin-left: 30rpx;
			background: rgba(255, 255, 255, 0.4);
			height: 62rpx;
			display: flex;
			align-items: center;
			padding: 0 20rpx;
			border-radius: 72rpx;
		}
		
		.icon-box{
			width: 64rpx;
			height: 64rpx;
			background: rgba(255,255,255,0.4);
			display: flex;
			align-items: center;
			justify-content: center;
			border-radius: 50%;
		}
		
		.poin {
			display: inline-block;
			background-color: $u-color-main;
			width: 20rpx;
			height: 20rpx;
			border-radius: 100%;
			box-shadow: 0 0 5px $u-color-main;
			margin-right: 10rpx;
		}
	
		.online {
			.poin {
				background-color: $u-color-green;
				box-shadow: 0 0 5px $u-color-green;
			}
		}
	
		.offline {
			.poin {
				background-color: $u-color-red;
				box-shadow: 0 0 5px $u-color-red;
			}
		}
	}
</style>
